//
//  Colum_NavViewController.m
//  YinHang
//
//  Created by 张亚哲 on 14/10/31.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "Colum_NavViewController.h"

@interface Colum_NavViewController ()<UITableViewDataSource,UITableViewDelegate,ASIHTTPRequestDelegate>{
    
    __weak IBOutlet UITableView *_tableView;
    NSMutableArray *state;//记录状态
    NSMutableArray *stateArr;//记录title
    
    NSMutableArray *navDataArr;//导航数据
    NSMutableDictionary *navDataDic;//导航内容
    MBProgressHUD *postHud;
    //参数
    ASIFormDataRequest *getDataRequest;//获取数据请求
    ASIFormDataRequest *postStateRequest;//发送修改请求
    NSString *action;
    NSDictionary *paramsDict;
    
    NSString *idStr;
}

@end

@implementation Colum_NavViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
}

-(void)viewDidLayoutSubviews{
    UIScreen *screen = [UIScreen mainScreen];
    self.view.frame = CGRectMake(0, 0, screen.bounds.size.width, screen.bounds.size.height - 64 - 35);
    _tableView.frame = self.view.frame;

}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    state = [NSMutableArray array];
    for (int i = 0; i < 10; i++) {
        state[i]= @"off";
    }
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.rowHeight = 60;
    [self getData];
    navDataArr = [NSMutableArray array];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark UItable Delegate Method
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"nav_cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = (UITableViewCell *)[[NSBundle mainBundle]loadNibNamed:@"Colum_navCell" owner:nil options:nil][0];
    }
    NSInteger row = indexPath.row;
    UILabel *lbl = (UILabel *)[cell.contentView viewWithTag:1];
    lbl.text = navDataDic[navDataArr[row]];
    UISwitch *sw = (UISwitch *)[cell.contentView viewWithTag:2];
    if ([state[row] isEqualToString:@"block"]) {
        [sw setOn:NO];
    }else{
        [sw setOn:YES];
    }
    sw.tag = row + 10;
    [sw addTarget:self action:@selector(swChange:) forControlEvents:UIControlEventValueChanged];
    return cell;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (!navDataArr || navDataArr.count != 0) {
        return navDataArr.count;
    }else{
        return 0;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#pragma mark IBAction Method
-(void)swChange:(id)sender{
    UISwitch *sw = sender;
    NSInteger row = sw.tag - 10;
    if ([sw isOn]) {
        state[row] = @"none";
    }else{
        state[row] = @"block";
    }
    //[_tableView reloadData];
    [self postState:stateArr[row] stateStr:state[row]];
}

#pragma mark Custom Method

-(void)getData{
    if (![Constants isExistenceNetwork]) {
        
    } else {
        if (!postHud || postHud.hidden == YES) {
            // 提示正在加载数据...
            postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            postHud.labelText = @"正在加载，请稍后...";
        }
        
        getDataRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
        getDataRequest.requestMethod = @"POST";
        // 设置超时时间
        getDataRequest.timeOutSeconds = 60;
        getDataRequest.delegate = self;
        // 设置参数
        action = @"DaohangLanmumain";
        paramsDict = [NSDictionary dictionary];
        paramsDict = @{@"uid":UNAME};//uid会员名
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,paramsStr];
        
        NSData *paramsData = [result toGBKEncodingData];
        getDataRequest.postBody = [paramsData mutableCopy];
        
        [getDataRequest startAsynchronous];
    }
}

-(void)postState:(NSString *)title stateStr:(NSString*)stateStr{
    if (![Constants isExistenceNetwork]) {
        
    } else {
        if (!postHud || postHud.hidden == YES) {
            // 提示正在加载数据...
            postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            postHud.labelText = @"正在修改，请稍后...";
        }
        
        postStateRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
        postStateRequest.requestMethod = @"POST";
        // 设置超时时间
        postStateRequest.timeOutSeconds = 60;
        postStateRequest.delegate = self;
        // 设置参数
        action = @"DaohangLanmuupdate";
        paramsDict = [NSDictionary dictionary];
        paramsDict = @{@"uid":UNAME,title:stateStr,@"id":idStr};//uid会员名
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,paramsStr];
        
        NSData *paramsData = [result toGBKEncodingData];
        postStateRequest.postBody = [paramsData mutableCopy];
        
        [postStateRequest startAsynchronous];
    }

}
#pragma mark - ASIHttpRequestDelegate method

- (void)requestFinished:(ASIHTTPRequest *)request {
    NSLog(@"%@",request.responseString);
    postHud.hidden = YES;
    NSError *err;
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
    
    // 1. 是否解析有错误
    if (!err) {
        
        // 2. 判断错误码
        NSInteger errorCode = [result[@"errorCode"]integerValue];
        
        if (errorCode == 0) {
            postHud.hidden = YES;
            if (request == getDataRequest) {
                //[SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
                navDataDic = result[@"info"];
                //navDataArr = navDataDic.allKeys;
                [state removeAllObjects];
                [navDataArr removeAllObjects];
                stateArr = [NSMutableArray array];
                for (NSString *str in navDataDic.allKeys) {
                    if ([str isEqualToString:@"ID"]) {
                        idStr = navDataDic[str];
                        _idstr = navDataDic[str];
                        continue;
                    }
                    if ([str rangeOfString:@"Title"].location != NSNotFound) {
                        [navDataArr addObject:str];
                    }else{
                        [stateArr addObject:str];
                    }
                    //[navDataArr sortUsingSelector:@selector(compare:)];
                    [navDataArr sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
                        NSString *str1 = [obj1 substringFromIndex:5];
                        NSString *str2 = [obj2 substringFromIndex:5];
                        if ([str1 intValue] > [str2 intValue]){
                            return NSOrderedDescending;
                        }
                        if ([str1 intValue] < [str2 intValue]){
                            return NSOrderedAscending;
                        }
                        return NSOrderedSame;
                    }];
                    [stateArr sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
                        NSString *str1 = [obj1 substringFromIndex:6];
                        NSString *str2 = [obj2 substringFromIndex:6];
                        if ([str1 intValue] > [str2 intValue]){
                            return NSOrderedDescending;
                        }
                        if ([str1 intValue] < [str2 intValue]){
                            return NSOrderedAscending;
                        }
                        return NSOrderedSame;
                    }];
                    
                }
                for (int i = 0; i < navDataArr.count; i++) {
                    state[i]= navDataDic[stateArr[i]];
                }
                _titleArr = [navDataArr mutableCopy];
                _titleDic = [navDataDic mutableCopy];
                [_tableView reloadData];//更新数据

            }else{
                [SVProgressHUD showSuccessWithStatus:@"修改成功"];
                }
        }
        
    } else {
        [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request{
    [SVProgressHUD showErrorWithStatus:@"服务器无法访问，请稍后再试!"];
}


-(void)dealloc{
    
    [getDataRequest cancel];
    [postStateRequest cancel];
    postHud = nil;
    getDataRequest = nil;
    postStateRequest = nil;
    _idstr = nil;
    _titleArr = nil;
}
//刷新数据
-(void)reFreshData{
    [self getData];
}

@end
